using Microsoft.EntityFrameworkCore;
using RealtimeCollabGame.Infrastructure.Persistence;
using RealtimeCollabGame.Infrastructure.Repositories;
using RealtimeCollabGame.Infrastructure.SignalR;
using RealtimeCollabGame.Application.Interfaces;
using RealtimeCollabGame.Application.Services;
using RealtimeCollabGame.Application.Handlers;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy = null; // 保持属性名大小写
        options.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter()); // 枚举序列化为字符串
    });
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 配置数据库
builder.Services.AddDbContext<GameContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));

// 配置SignalR
builder.Services.AddSignalR();

// 注册仓储
builder.Services.AddScoped<IGameRepository, GameRepository>();
builder.Services.AddScoped<IPlayerRepository, PlayerRepository>();

// 注册命令处理器
builder.Services.AddScoped<CreateGameCommandHandler>();
builder.Services.AddScoped<JoinGameCommandHandler>();
builder.Services.AddScoped<LeaveGameCommandHandler>();
builder.Services.AddScoped<PaintActionCommandHandler>();
builder.Services.AddScoped<DeleteGameCommandHandler>();
builder.Services.AddScoped<SetPlayerReadyCommandHandler>();
builder.Services.AddScoped<StartGameCommandHandler>();
builder.Services.AddScoped<GetGameQueryHandler>();
builder.Services.AddScoped<GetGameByCodeQueryHandler>();
builder.Services.AddScoped<GetAllGamesQueryHandler>();

// 注册应用服务
builder.Services.AddScoped<GameService>();

// 配置CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.WithOrigins("http://localhost:5173", "http://localhost:3000", "http://localhost:8080")
              .AllowAnyMethod()
              .AllowAnyHeader()
              .AllowCredentials();
    });
});

var app = builder.Build();

// 自动迁移数据库
using (var scope = app.Services.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<GameContext>();
    context.Database.Migrate();
}

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseCors("AllowAll");

app.UseAuthorization();

app.MapControllers();

// 映射SignalR Hub
app.MapHub<GameHub>("/gamehub");

app.Run();
